package components;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigInteger;

public class Decrypter {

	/**
	 * Decipher a given ciphertext into a plaintext, represented as a String.
	 * This method will read from ciphertext.txt and the deciphered plaintext
	 * will be saved to decryptedPlaintext.txt.
	 * 
	 * @param cipherText - Array of enciphered characters.
	 * @param privKey - Private Key
	 * @return msg - Plaintext
	 */
	public String decipher(BigInteger[] cipherText, RSAKey privKey){
		String msg = "";
		for(int i = 0; i<cipherText.length; i++){//Iterate through BigIntegers in cipherText
			char deciphered = (char) cipherText[i].modPow(privKey.getExp(), privKey.getN()).intValue(); //Decipher
			msg += deciphered; //Append deciphered char to msg
		}
		
		try{
			//read ciphertext
			FileReader reader = new FileReader("ciphertext.txt");
			BufferedReader br = new BufferedReader(reader);
			@SuppressWarnings("unused")
			String line;
			line = br.readLine();
			
			//create new decrypted plaintext
			FileWriter decPt = new FileWriter("decryptedPlaintext.txt");
			BufferedWriter writer = new BufferedWriter(decPt);
			writer.write(msg);
			writer.close();

//			String[] splitted = line.split("[ ]+");
//			for(String enciphered:splitted){
//				
//				Integer myint1 = Integer.valueOf(enciphered);
//			}
//			

//			String plainText = decipher(line);
//			
//			StringBuilder toFile = new StringBuilder();
//			for(BigInteger chunk : filename) {
//			    toFile.append(chunk.intValue()).append(" ");
//			}
//			 
//			PrintStream out = new PrintStream(new FileOutputStream("ciphertext.txt"));
//			System.setOut(out);
//			out.close();
			
		}catch(FileNotFoundException ex){
			System.out.println("Input file not found!");

		} catch (IOException e) {
			System.out.println("Cannot read from file!");
			e.printStackTrace();
		}
		
		return msg;
	}
	public static void main(String[] args) {

	}

}
